package utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BeanUtil {

    @SuppressWarnings("unchecked")
    public static <T> T getFieldValueByName(Object o, String fieldName, Class<T> tClass) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        String firstLetter = fieldName.substring(0, 1).toUpperCase();
        String getter = "get" + firstLetter + fieldName.substring(1);
        Method method = o.getClass().getMethod(getter);
        Object value = method.invoke(o);
        return (T) value;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getFieldValueByName(Object o, String fieldName, T value) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        String firstLetter = fieldName.substring(0, 1).toUpperCase();
        String getter = "get" + firstLetter + fieldName.substring(1);
        Method method = o.getClass().getMethod(getter, value.getClass());
        return (T) method.invoke(o, value);
    }

    public static <T> void setFieldValueByName(Object o, String fieldName, T value) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        String firstLetter = fieldName.substring(0, 1).toUpperCase();
        String getter = "set" + firstLetter + fieldName.substring(1);
        Method method = o.getClass().getMethod(getter, value.getClass());
        method.invoke(o, value);
    }
}